package com.itheima.ssm.service.impl;

import com.itheima.ssm.dao.RoleMapper;
import com.itheima.ssm.dao.UsersMapper;
import com.itheima.ssm.service.IUserService;
import com.itheima.ssm.vo.Permission;
import com.itheima.ssm.vo.Role;
import com.itheima.ssm.vo.Users;
import com.itheima.ssm.vo.UsersPer;
import com.sun.deploy.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service("userService")
@Transactional
public class UserServiceImpl implements IUserService {

    @Autowired
    private UsersMapper userDao;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    public void addRoleToUser(String userId, String[] roleIds) {

        for(String roleId:roleIds){
            userDao.addRoleToUser(userId,roleId);
        }
    }

    @Override
    public List<Role> findOtherRoles(String userId) {
        List<Role> roles = new ArrayList<>();
        try {
            roles = userDao.findOtherRoles(userId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return roles;
    }

    @Override
    public Users findById(String id) throws Exception{
        Users byId = null;
        try {
            byId = userDao.findById(id);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return byId;
    }

    @Override
    public void save(Users userInfo) throws Exception {
        //对密码进行加密处理
        userInfo.setPassword(bCryptPasswordEncoder.encode(userInfo.getPassword()));
        userDao.save(userInfo);
    }

    @Override
    public List<Users> findAll() throws Exception {
        return userDao.findAll();
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Users userInfo = null;
        try {
            userInfo = userDao.findByUsername(username);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //处理自己的用户对象封装成UserDetails
         //User user=new User(userInfo.getUsername(),"{noop}"+userInfo.getPassword(),getAuthority(userInfo.getRoles()));
        List<GrantedAuthority> authority = getAuthority(userInfo.getRoles(), null);
        UsersPer user = new UsersPer(userInfo.getUsername(),
                userInfo.getPassword(),
                "0".equals(userInfo.getStatus()) ? false : true, true, true, true, authority);
        return user;
    }

    /*public static void main(String[] args) {

        List<String> list = new ArrayList<String>();
        list.add("a");
        list.add("b");
        list.add("c");
        list.add("d");
        System.out.println(list);


        List<String> list2 = new ArrayList<String>();
        list2.add("1");
        list2.add("2");
        list2.add("3");
        list2.add("4");


        String join = StringUtils.join(list, ",");

        System.out.println(join);

    }*/



    //作用就是返回一个List集合，集合中装入的是角色描述
    public List<GrantedAuthority> getAuthority(List<Role> roles, List<Permission> permissions) {
        //String permissionsString = StringUtils.join(permissions, ",");
        String permissionsString =  "1,2,3,4";
        String rolesString = null;
        for (Role role : roles) {
            rolesString = "ROLE_" + role.getRoleName();
        }
        String rolesPerString = rolesString +","+ permissionsString;
        List<GrantedAuthority> grantedAuthorities = AuthorityUtils.commaSeparatedStringToAuthorityList(rolesPerString);
        return grantedAuthorities;
    }
}
